<?php

/**
 * @property string $name
 * @property double $latitude
 * @property double $longitude
 * @property integer $city_id
 * @property integer $distance
 *
 */
class LocationModel extends BaseModel
{
	public function tableName()
	{
		return '{{location}}';
	}

	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public function getNearestCity($latitude, $longitude, $country)
    {
        $sql = 'SELECT
                    t.id AS city_id,
                    6371 * ACOS(SIN(t.latitude1) * SIN(t.latitude2)+COS(t.latitude1)*COS(t.latitude2)*COS(t.theta)) AS distance
                FROM
                (
                    SELECT
                        c.id,
                        RADIANS(c.latitude) AS latitude1,
                        RADIANS(%s) AS latitude2,
                        RADIANS(c.longitude-%s) AS theta
                    FROM
                        oak_city c
                    WHERE
                        c.country = :country
                ) t
                ORDER BY
                    distance
                LIMIT 1;';
        $sql = sprintf($sql, $latitude, $longitude);

        $city = Yii::app()->db->createCommand($sql)
                              ->bindParam(':country', $country)
                              ->queryRow();
        if(!$city)
        {
            return array('id' => CONST_DEFAULT_CITY_ID, 'distance' => 0);
        }
        return $city;
    }
}
